package it.niedermann.android.markdown.markwon.plugins

import io.noties.markwon.base.AbstractMarkwonPlugin
import io.noties.markwon.base.MarkwonPlugin
import io.noties.markwon.base.MarkwonSpansFactory
import io.noties.markwon.base.SpanFactory
import io.noties.markwon.base.core.CoreProps.LINK_DESTINATION
import it.niedermann.android.markdown.markwon.span.InterceptedURLSpan
import org.commonmark.node.Link
import java.util.LinkedList
import java.util.function.Function

class LinkClickInterceptorPlugin : AbstractMarkwonPlugin() {
    private val onLinkClickCallbacks: MutableCollection<Function<String, Boolean>> = LinkedList()
    override fun configureSpansFactory(builder: MarkwonSpansFactory.Builder) {
        super.configureSpansFactory(builder)
        builder.setFactory(
            Link::class.java,
            SpanFactory { configuration, props ->
                InterceptedURLSpan(
                    onLinkClickCallbacks,
                    LINK_DESTINATION[props]
                )
            } )
    }

    fun registerOnLinkClickCallback(callback: Function<String, Boolean>) {
        onLinkClickCallbacks.add(callback)
    }

    companion object {
        fun create(): MarkwonPlugin {
            return LinkClickInterceptorPlugin()
        }
    }
}